package cn.topcodes.tcsf.app.service.impl;

import cn.topcodes.tcsf.admin.domain.entity.SysMenu;
import cn.topcodes.tcsf.admin.domain.form.NestableSort;
import cn.topcodes.tcsf.app.domain.entity.HelpArticle;
import cn.topcodes.tcsf.app.domain.entity.HelpArticleCatalog;
import cn.topcodes.tcsf.admin.commons.generic.GenericService;
import cn.topcodes.tcsf.app.service.HelpArticleCatalogService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * 类别 服务
 *
 * @author Yvan
 */
@Service
public class HelpArticleCatalogServiceImpl extends GenericService<HelpArticleCatalog> implements HelpArticleCatalogService {

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void saveSort(List<NestableSort> sort) {
        tranSaveSort(sort, null);
    }

    @Override
    public List<HelpArticleCatalog> findByParent(Long parentCatalogId) {
        Example example = this.buildExample();
        if(parentCatalogId != null) {
            example.or().andEqualTo(HelpArticleCatalog.FIELD_PARENT_ID, parentCatalogId);
        }else {
            example.or().andIsNull(HelpArticleCatalog.FIELD_PARENT_ID);
        }
        return this.findAll(example);
    }

    private void tranSaveSort(List<NestableSort> sort, Long parentId) {
        if(sort == null) return;
        for(int i = 0 ; i < sort.size() ; i ++ ) {
            NestableSort s = sort.get(i);
            HelpArticleCatalog helpArticleCatalog = this.findOne(s.getId());
            helpArticleCatalog.setSort(i);
            helpArticleCatalog.setParentId(parentId);
            this.update(helpArticleCatalog);
            tranSaveSort(s.getChildren(),s.getId());
        }
    }
}
